package com.work_attendance.login.controller;

import com.work_attendance.common.utils.SecurityUtils;
import com.work_attendance.user.entity.User;
import com.work_attendance.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;
    private User user;

    /**
     *
     * 进入登录页面
     */
    @RequestMapping("index")
    public String login(){

        return "login";
    }

    @ResponseBody/*表示返回的是响应体，而不是页面跳转*/
    @RequestMapping("check")
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //查数据库 调用md5加密后 和查出的密码比对
        User user=userService.findUserByUsername(username);
        //校验成功 用户信息存入session 返回成功信息
        //校验失败 返回错误失败
        if(user!=null){
            if(SecurityUtils.checkPassword(password,user.getPassword())){
                request.getSession().setAttribute("userinfo",user);
                return "login_succ";
            }
            else{
                return "login_fail";
            }
        }else{
            return "login_fail";
        }
    }

    @RequestMapping("/crUser")
    @ResponseBody
    public String createUser(@RequestBody User user) throws Exception {
        userService.createUser(user);
        return "succ";
    }
}
